package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bean.*;
import com.example.bean.dto.BlockchainCompanyInfoDTO;
import com.example.bean.query.*;
import com.example.bean.vo.BlockchainCompanyInfo;
import com.example.common.BaseContext;
import com.example.common.InvokeResult;
import com.example.common.R;
import com.example.dao.BlockchainCompanyInfoRepository;
import com.example.service.BlockchainApplicationService;
import com.example.service.SysDictService;
import com.example.utils.PDFUtils;
import com.example.utils.ReadExcel;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import com.example.service.BlockchainCompanyInfoService;
import com.example.service.UserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("stage-api")
public class EmployeeController {

    @Autowired
    private BlockchainApplicationService service;
    @Autowired
    private BlockchainCompanyInfoRepository repository;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    BlockchainCompanyInfoService blockchainCompanyInfoService;

    @Autowired
    PDFUtils pdfUtils;

    @Autowired
    UserService userService;

    Date date = new Date();

    @PostMapping("/login")
    public InvokeResult login(HttpServletRequest request,@RequestBody sysUser user){

        LambdaQueryWrapper<sysUser> wrapper = new LambdaQueryWrapper<sysUser>();
        wrapper.eq(sysUser::getUsername,user.getUsername());
        wrapper.eq(sysUser::getPassword,user.getPassword());

        sysUser one = userService.getOne(wrapper);

        if(one != null){
            BaseContext.setThreadLocal((long) one.getId());
            request.getSession().setAttribute("user",BaseContext.getThreadLocal());
            return InvokeResult.success("登录成功！");

        }else{
            return InvokeResult.error("登录失败！");
        }

    }

    @PostMapping("/admin/blockchain/list")
    public InvokeResult list(@RequestBody BlockchainApplicationQuery query) {


        Page<blockchainCompanyInfo> pg = new Page<blockchainCompanyInfo>(1, query.getPageSize());

        LambdaQueryWrapper<blockchainCompanyInfo> wrapper = new LambdaQueryWrapper<blockchainCompanyInfo>();

        wrapper.like(query.getName()!=null,blockchainCompanyInfo::getName,query.getName());
        wrapper.like(query.getPark()!=null,blockchainCompanyInfo::getPark,query.getPark());
        wrapper.like(query.getSubmitDate()!=null,blockchainCompanyInfo::getSubmitDate,query.getSubmitDate());
        wrapper.like(query.getAuditDate()!=null,blockchainCompanyInfo::getAuditDate,query.getAuditDate());


        blockchainCompanyInfoService.page(pg,wrapper);



        List<BlockchainApplicationQuery> list = new ArrayList<>();
        for (blockchainCompanyInfo info : pg.getRecords()) {
            BlockchainApplicationQuery q = new BlockchainApplicationQuery();
            q.setName(info.getName());
            q.setPark(info.getPark());
            q.setSubmitDate(info.getSubmitDate().toLocalDate());
            q.setAuditDate(info.getAuditDate().toLocalDate());
            q.setAuditStatus(info.getAuditStatus());
            list.add(q);

        }


        return InvokeResult.success(list);


    }


    @GetMapping("/admin/blockchain/detail")
    public InvokeResult detail(Long id) {
        System.out.println(id);
        blockchainCompanyInfo info = blockchainCompanyInfoService.getById(515);

        return InvokeResult.success(info);
    }

    @GetMapping("/admin/blockchain/delete")
    public InvokeResult delete(Integer id) {

        System.out.println(id);
        blockchainCompanyInfoService.removeById(id);

        return InvokeResult.success("0","删除成功！");
    }


    @PostMapping("/admin/blockchain/audit")
    public InvokeResult update(@RequestBody blockchainCompanyInfo info) {
        blockchainCompanyInfoService.updateById(info);
        return InvokeResult.success("0","更新成功！");
    }


    @PostMapping("/admin/blockchain/import")
    public InvokeResult exportExcel(@ApiParam(value = "上传多个excel文件", required = true)@RequestParam(value = "files") MultipartFile[] files) {

        Workbook workbook = null;
        StringBuilder infoBuilder = new StringBuilder();
        int successcount = 0;
        int failcount = 0;
        int allcount = 0;


        for (MultipartFile file : files) {
            allcount++;
            infoBuilder.append(file.getOriginalFilename()).append("导入情况：");
            try {

                if (file.getOriginalFilename().endsWith("xlsx")) {
                    workbook = new XSSFWorkbook(file.getInputStream());
                } else if (file.getOriginalFilename().endsWith("xls")) {
                    workbook = new HSSFWorkbook(file.getInputStream());
                } else {
                    workbook = null;
                    infoBuilder.append(file.getName()).append("导入失败原因：").append("文件不为excel文件或excel文件有误，请使用模板文件");
                    infoBuilder.append("<br/>");
                    failcount++;
                }
            } catch (IOException e) {

                workbook = null;
                failcount++;
                infoBuilder.append(file.getName()).append("导入失败原因：").append("读文件失败");
                infoBuilder.append("<br/>");
            }

            if (workbook != null) {
                ReadExcel a = new ReadExcel();
                Map<String, List<String>> sysDicts = sysDictService.getAllDict();
                BlockchainCompanyInfoDTO dto = new BlockchainCompanyInfoDTO();


                if (dto != null) {
                    BlockchainCompanyInfo existsinfo = service.getcreditid(dto.getGeneralCreditCode());
                    if (existsinfo != null) {
                        failcount++;
                        infoBuilder.append("导入失败，原因:<br/>统一信用代码已经存在，请重新确认");
                        infoBuilder.append("<br/>");
                    } else {
                        BlockchainCompanyInfo info = BeanMapper.map(dto, BlockchainCompanyInfo.class);

                        info.setIsDelete(false);
                        info.setAuditStatus(0);
                        info.setTianxiestatus(1);

                        System.out.println(info);
                        blockchainCompanyInfo b = new blockchainCompanyInfo();
                        b.setAddress(info.getAddress());
                        b.setAuditStatus(info.getAuditStatus());
                        b.setBusinessScope(info.getBusinessScope());
                        b.setName("企业名称aaa");
                        b.setPark("海淀区");
                        b.setSubmitDate(LocalDateTime.now());
                        b.setAuditDate(LocalDateTime.now());
                        b.setCreatedDate(LocalDateTime.now());
                        b.setLastModifiedDate(LocalDateTime.now());
                        b.setFoundationDate(LocalDateTime.now());
                        b.setIssueDate(LocalDateTime.now());
                        b.setBuildTeamDate(LocalDateTime.now());
                        b.setTianxiestatus(info.getTianxiestatus());
                        b.setGeneralCreditCode(info.getGeneralCreditCode());
                        b.setLegalPerson(info.getLegalPerson());
                        b.setAdvanceName(info.getAdvanceName());
                        b.setCity(info.getCity());
                        b.setProvince(info.getProvince());
                        b.setCompanyType(info.getCompanyType());

                        blockchainCompanyInfoService.save(b);

                        service.savenewdata(dto, info.getId());


                        successcount++;

                        infoBuilder.append(file.getOriginalFilename()).append("导入成功");
                        infoBuilder.append("<br/>");
                    }
                } else {
                    failcount++;
                }


            }
        }
        infoBuilder.append("一共上传：").append(String.valueOf(allcount)).append("个文件");
        infoBuilder.append("<br/>");
        infoBuilder.append("上传成功：").append(String.valueOf(successcount)).append("个文件");
        infoBuilder.append("<br/>");
        infoBuilder.append("上传失败：").append(String.valueOf(failcount)).append("个文件");
        infoBuilder.append("<br/>");
        return InvokeResult.success("0", infoBuilder.toString());
    }

//    @GetMapping("/admin/blockchain/exportExcel")
//    public InvokeResult download(BlockchainApplicationQuery query){
//
//        LambdaQueryWrapper<blockchainCompanyInfo> wrapper = new LambdaQueryWrapper<blockchainCompanyInfo>();
//        wrapper.eq(blockchainCompanyInfo::getId,515);
//
//        blockchainCompanyInfo one = blockchainCompanyInfoService.getOne(wrapper);
//
//        Map<String,String> m = new HashMap<>();
//
//        m.put("f1",one.getName());
//        m.put("f2",one.getGeneralCreditCode());
//        m.put("f3",one.getEnterpriseType());
//        m.put("f4",one.getCompanyType());
//        m.put("f5",String.valueOf(one.getCreatedDate()));
//
//        pdfUtils.test(m);
//
//        return InvokeResult.success(one);
//    }


    @GetMapping("/admin/blockchain/exportExcel")
    @ApiOperation(value = "导出excel，数据较多的情况下比较慢，需要提示用户，同步处理")
    public void exportExcel(BlockchainExportQuery query,HttpServletRequest request,
                            HttpServletResponse res){

        query.setIds("515");
        query.setName("区块链产品");
        query.setPark("海淀园");
        String str="models.xlsx";
        String path = request.getSession().getServletContext().getRealPath("");
        path=path.substring(0,path.length()-5);
        path+="files/";
        String modelpath="F:\\springboot系统demo\\backend\\src\\main\\resources\\model\\"+str;
        String newpath=path+ DateUtil.formatDate(new Date(),"yyyyMMddHHmmss")+"/";
        File file=new File("F:\\springboot系统demo\\backend\\src\\main\\resources\\model\\");
        file.mkdirs();
        File file1=new File("F:\\springboot系统demo\\backend\\src\\main\\resources\\model\\"+str);
        String ids = query.getIds();
        List<BlockchainCompanyInfo> infos;
        if(StringUtils.isBlank(ids)){
            //todo 分批查库
            infos = service.findAll(query);
        }else{
            infos=service.getRecordByIds(ids);
        }
        ExportExcel excel=new ExportExcel();
        excel.exportdata(str,modelpath,newpath,infos,service);
        try {
            //			res.reset();
            res.setContentType("application/octet-stream; charset=utf-8");
            res.setHeader("content-type", "application/octet-stream;charset=UTF-8");
            res.setHeader("Content-Disposition", "attachment; filename="+ file1.getAbsolutePath());
            InputStream is = new BufferedInputStream(new FileInputStream(file1));
            OutputStream oStream = res.getOutputStream();
            IOUtils.copy(is, oStream);
            is.close();
            oStream.close();
//            for(File defile:file.listFiles()) {
//                defile.delete();
//            }
//            file.delete();
//            file1.delete();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }



}
